package com.mk.cloud.common.service.core;

import act.controller.Controller;
import act.validation.NotBlank;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mk.cloud.common.domain.CpUser;
import org.osgl.util.S;import com.mk.cloud.common.util.S2;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.osgl.mvc.annotation.PostAction;
import org.osgl.mvc.annotation.ResponseStatus;
import org.osgl.mvc.result.Result;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("unused")
@Controller("core")
public class QueryService extends Controller.Base {
    private static final String EMPTY = " ";
    private static final String ASC = "ASC";
    private static final String DESC = "DESC";
    @Inject
    private CpUser.Mapper cpUserMapper;

    @PostAction("jqgrid.json")
    @ResponseStatus(200)
    public Result query(String page,
                        String rows,
                        @NotBlank String __sql_code,
                        String __postData__,
                        String __tableName__,
                        String __column_search__,
                        String __column_summary__,
                        String __type_ex__,
                        String sidx,
                        String sord,
                        String groupBy,
                        String _group_sortable_,
                        String limit_ex,
                        String _tree_,
                        String filters,
                        String search) {

        //region 参数初始化
        PageQuery<Map> query = new PageQuery<>();
        JSONArray tableName = S.isNotBlank(__tableName__) ? JSON.parseArray(__tableName__) : new JSONArray();
//        JSONArray type_ex = S2.isNotBlank(__type_ex__) ? JSON.parseArray(__type_ex__) : new JSONArray();
//        JSONArray column_search = S2.isNotBlank(__column_search__) ? JSON.parseArray(__column_search__) : new JSONArray();
        //endregion

        //region 分页处理
        if (!S.isAnyBlank(page, rows)) {
            int page_ = Integer.parseInt(page);
            int row_ = Integer.parseInt(rows);
            if (S.isNotBlank(limit_ex)) {
                row_ = Integer.parseInt(limit_ex);
            }
            query.setPageNumber(page_);
            query.setPageSize(row_);
        } else {
            query.setPageSize(Long.MAX_VALUE);
        }
        //endregion

        //region 处理排序
        String orderStr = "";
        if (S.isNotBlank(sidx)) {
            orderStr = sidx;
            if (S.isNotBlank(sord)) {
                orderStr += EMPTY;
                orderStr += sord;
            }
        }
        if (!orderStr.isEmpty()) {
            orderStr = orderStr.replace("asc,  asc", EMPTY).replace("desc,  desc", EMPTY);
            Matcher m = Pattern.compile("\\w+[^,\\s]*").matcher(orderStr);
            StringBuffer result = new StringBuffer();
            while (m.find()) {
                String param = m.group();
                if (StringUtils.equalsIgnoreCase(param, ASC) || StringUtils.equalsIgnoreCase(param, DESC)) {
                    continue;
                }
                for (int k = 0; k < tableName.size(); k++) {
                    JSONArray table_name = tableName.getJSONArray(k);
                    if (StringUtils.equalsIgnoreCase(table_name.getString(0), param)) {
                        param = table_name.getString(1) + "." + param;
                        break;
                    }
                }
                m.appendReplacement(result, param);
            }
            m.appendTail(result);

            String order = result.toString();

            //分组字段不排序
            if (S.isNotBlank(_group_sortable_)) {
                String[] _group_sortable_s = _group_sortable_.split("\\+");
                for (String o : _group_sortable_s) {
                    order = S2.replaceReg(order, o + "\\s(asc|desc)", "");
                }
                String[] dx = order.split(",");
                StringBuilder sb = new StringBuilder();
                for (String oo : dx) {
                    if (StringUtils.isNotBlank(oo)) {
                        sb.append(oo);
                    }
                }
                order = sb.toString();
            }
            query.setOrderBy(order);
        }
        //endregion

        //不支持分组
        //不支持自定义查询
        //region 处理参数
        if (S.isNotBlank(__postData__)) {
            JSONObject param = JSON.parseObject(__postData__);
            Map<String, Object> params = new HashMap<>();
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                if (entry.getValue() != null && (StringUtils.isBlank(entry.getValue().toString()) || StringUtils.equalsIgnoreCase(entry.getValue().toString(), "null") || StringUtils.equalsIgnoreCase(entry.getValue().toString(), "undefined"))) {
                    params.put(entry.getKey(), null);
                } else {
                    params.put(entry.getKey(), entry.getValue());
                }
            }
            query.setParas(params);
        }
        //endregion
        //region 查询开始
        cpUserMapper.getSQLManager().pageQuery(__sql_code, Map.class, query);
        Map<String, Object> result = new HashMap<>();
        result.put("total", query.getTotalPage());
        result.put("records", query.getTotalRow());
        result.put("rows", query.getList());
//        result.put("userdata", toSummary());
        //endregion
        return renderJson(result);
    }
}
